package startup

import (
	prom "github.com/go-kratos/kratos/contrib/metrics/prometheus/v2"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/logging"
	"github.com/go-kratos/kratos/v2/middleware/metadata"
	"github.com/go-kratos/kratos/v2/middleware/metrics"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/middleware/validate"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"gotham-plan-manage/internal/conf"
	"gotham-plan-manage/internal/interfaces/facade"
	"gotham-plan-manage/pkg/interceptor"
	"gotham-plan-manage/proto/gotham-plan-manage-proto/plan"
	"gotham-plan-manage/proto/gotham-plan-manage-proto/task"
)

// NewGRPCServer new a gRPC startup.
func NewGRPCServer(c *conf.Server, planApi *facade.PlanServer, taskApi *facade.TaskServer, logger log.Logger) *grpc.Server {
	var opts = []grpc.ServerOption{
		grpc.Middleware(
			recovery.Recovery(),
			tracing.Server(),
			validate.Validator(),
			metadata.Server(),
			interceptor.Auth(),
			logging.Server(logger),
			metrics.Server(
				metrics.WithSeconds(prom.NewHistogram(conf.MetricSeconds)),
				metrics.WithRequests(prom.NewCounter(conf.MetricRequests)),
			),
		),
	}
	if c.Grpc.Network != "" {
		opts = append(opts, grpc.Network(c.Grpc.Network))
	}
	if c.Grpc.Addr != "" {
		opts = append(opts, grpc.Address(c.Grpc.Addr))
	}
	if c.Grpc.Timeout != nil {
		opts = append(opts, grpc.Timeout(c.Grpc.Timeout.AsDuration()))
	}
	srv := grpc.NewServer(opts...)
	plan.RegisterPlanApiServer(srv, planApi)
	task.RegisterTodoTaskApiServer(srv, taskApi)
	return srv
}
